package server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.log.Log;

import page.PageManagerMainFactory;
import abstractclass.PageManagerAbstract;
import tools.SysAlert;
import model.UserInfoBase;
import model.UserModel;
import model.transfermodel.BeatPackage;
import DBtools.HeartBeatBO;
import DBtools.UserBO;

public class UpdatePhoneNumServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		out.println("<html><body><h1>This is a servlet test UpdatePhoneNumServlet . welcome</h1></body></html>");
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		String imei = req.getParameter("imei");
		String phomenum =  req.getParameter("phonenum");
		
		SysAlert.info("UpdatePhoneNumServlet", imei+"");
		SysAlert.info("UpdatePhoneNumServlet", phomenum+"");
		
		HeartBeatBO bo = new HeartBeatBO();
		List list = bo.findByImei(imei);
		
		if(list.size() != 0){
			HashMap<String, Object> map = (HashMap<String, Object>) list.get(0);
			BeatPackage beat = new BeatPackage();
			beat.imei = imei;
			beat.phoneNum = phomenum;
			beat.delay = (int) map.get("delay");
			beat.imsi = (String) map.get("imsi");
			beat.latitude = (double) map.get("lantitude");
			beat.longtitude = (double) map.get("longtitude");
			beat.owner = (String) map.get("owner");
			beat.LocalIpAddress = (String) map.get("localip");
			beat.wifiIP = (String) map.get("wifiip");
			bo.updateHeartBeat(beat);
			
			String username = (String) req.getSession().getAttribute("username");
			UserInfoBase info = (UserInfoBase) req.getSession().getAttribute(username);
			PageManagerMainFactory factory = new PageManagerMainFactory();
			UserModel model = new UserModel();
			UserBO userbo = new UserBO();
			List userlist = userbo.find(username);
			HashMap<String, Object> usermap = (HashMap<String, Object>) userlist.get(0);
			model.user = username;
			model.userlevel = (int) usermap.get("userlevel");
			info.pageManeger = (PageManagerAbstract) factory.getPageManager(model);
		}
		
		req.getRequestDispatcher("main.jsp").forward(req, resp);
	}

}
